<template>
  <div>
    <el-dialog class="edit-box"
               :title="dialog.title"
               :visible.sync="dialog.visible"
               :close-on-click-modal="false"
               append-to-body
               top="5vh"
               width="80%">
      <el-tabs v-model="tabsSelectedId" type="card">
        <el-tab-pane label="基本信息" name="recordEditBasic">
          <record-edit-basic
            ref="recordEditBasic"
            :visible="dialog.visible"
            :detail-data="detailInfo"
            @on-input="handleInputChange"
            v-bind="$attrs"/>
        </el-tab-pane>
        <el-tab-pane label="社保信息" name="recordEditSocial">
          <record-edit-social
            ref="recordEditSocial"
            :visible="dialog.visible"
            :detail-data="detailInfo"
            @on-input="handleInputChange"
            v-bind="$attrs"/>
        </el-tab-pane>
        <el-tab-pane label="合同信息" name="recordEditContract">
          <record-edit-contract
            ref="recordEditContract"
            :visible="dialog.visible"
            :detail-data="detailInfo"
            @on-input="handleInputChange"
            v-bind="$attrs"/>
        </el-tab-pane>
        <el-tab-pane label="商业险" name="recordEditCommercial">
          <record-edit-commercial
            ref="recordEditCommercial"
            :visible="dialog.visible"
            :detail-data="detailInfo"
            @on-input="handleInputChange"
            v-bind="$attrs"/>
        </el-tab-pane>
        <el-tab-pane label="材料信息" name="recordEditFiles">
          <record-edit-files
            ref="recordEditFiles"
            :visible="dialog.visible"
            :detail-data="detailInfo"
            :form-value="editInfo.data"
            :tabs-selected-id="tabsSelectedId"
            @on-input="handleInputChange"
            v-bind="$attrs"
            v-on="$listeners"/>
        </el-tab-pane>
        <el-tab-pane label="薪资" name="recordEditSalary">
          <record-edit-salary
            ref="recordEditSalary"
            :visible="dialog.visible"
            :detail-data="detailInfo"
            @on-input="handleInputChange"
            v-bind="$attrs"/>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { debounce } from 'lodash'
  import { createRecordAPI, updateRecordAPI, getRecordDetailAPI } from '@/api/employee/record'
  import commonMixins from '@/mixins/common'
  import RecordEditBasic from './recordEditBasic'
  import RecordEditSocial from './recordEditSocial'
  import RecordEditContract from './recordEditContract'
  import RecordEditCommercial from './recordEditCommercial'
  import RecordEditFiles from './recordEditFiles'
  import RecordEditSalary from './recordEditSalary'

  export default {
    name: 'RecordEdit',
    mixins: [commonMixins],
    inheritAttrs: true,
    components: {
      RecordEditBasic,
      RecordEditSocial,
      RecordEditContract,
      RecordEditCommercial,
      RecordEditFiles,
      RecordEditSalary
    },
    data() {
      return {
        tabPaneList: ['recordEditBasic', 'recordEditSocial', 'recordEditContract', 'recordEditCommercial', 'recordEditFiles', 'recordEditSalary'], // pane列表
        dialog: {
          status: 'create',
          visible: false, // 是否显示
          title: '添加'
        },
        formParams: { // 编辑需要的参数
        },
        editInfo: { // 编辑表单
          id: undefined,
          data: {
            ...this.formParams
          },
          rules: {},
          disabled: false // 处理编辑，某些项禁止编辑
        },
        tabsSelectedId: 'recordEditBasic', // tab页面
        detailInfo: null
      }
    },
    props: {
      visible: {
        type: [Boolean],
        required: true,
        default: false
      },
      detailData: {
        type: Object,
        default() {
          return null
        }
      }
    },
    computed: {},
    methods: {
      validateTabPaneForm() { // 验证form，返回存在form错误的第一个tab值
        let { tabPaneList } = this
        // 遍历tabTane
        tabPaneList.forEach((item, index) => {
          this.$refs[item] && this.$refs[item].$refs['editInfo'].validate((valid, object) => {
          })
        })
        // 返回第一个tab有form提示错误的
        let errorTabPaneValue = tabPaneList.find((item, index) => {
          let isError = false
          this.$refs[item] && this.$refs[item].$refs['editInfo'].validate((valid, object) => {
            if (!valid) {
              isError = true
            }
          })
          return isError
        })
        // console.log(errorTabPaneValue)
        return errorTabPaneValue
      },
      handleInputChange(data) { // 输入框值变化事件
        this.editInfo.data = {
          ...this.editInfo.data,
          ...data
        }
      },
      handleEditSubmit: debounce(function() { // 编辑，提交，防抖
        // console.log(this.$refs)
        let errorTabPaneValue = this.validateTabPaneForm()
        if (errorTabPaneValue) { //如果验证不通过，就自动跳到有问题的tab页
          this.tabsSelectedId = errorTabPaneValue
        } else {
          if (this.editInfo.id) {
            this.updateData()
          } else {
            this.createData()
          }
        }
      }, 300),
      async createData() { // 添加－请求数据
        try {
          let { name } = this.editInfo.data
          let response = await createRecordAPI({
            ...this.editInfo.data,
            ...{
              name: name.trim()
            }
          })
          let result = response
          if (+result.code === 200) {
            this.dialog.visible = false
            this.$notify({
              title: '成功',
              message: '添加成功！',
              type: 'success',
              duration: 2000
            })
            this.$emit('create')
          } else {
            this.$notify.error({
              title: '错误',
              message: result.msg || '添加失败！'
            })
          }
        } catch (error) {
          // console.log(error)
          this.$notify.error({
            title: '错误',
            message: error.message || '添加失败！'
          })
        }
      },
      async updateData() { // 修改－请求数据
        try {
          //console.log(this.editInfo.data);
          let { name } = this.editInfo.data
          let response = await updateRecordAPI({
            ...this.editInfo.data,
            ...{
              id: this.editInfo.id,
              name: name.trim()
            }
          })
          let result = response
          if (+result.code === 200) {
            this.dialog.visible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.$emit('update')
          } else {
            this.$notify.error({
              title: '错误',
              message: result.msg || '编辑失败！'
            })
          }
        } catch (error) {
          // console.log(error)
          this.$notify.error({
            title: '错误',
            message: error.message || '编辑失败！'
          })
        }
      },
      async getRecordDetailData(data) { // 获取员工档案详情－请求数据
        try {
          let response = await getRecordDetailAPI({
            id: data.id
          })
          let result = response
          if (+result.code === 200) {
            this.detailInfo = result.data
          } else {
            this.$notify.error({
              title: '错误',
              message: result.msg || '获取失败！'
            })
          }
        } catch (error) {
          // console.log(error)
          this.$notify.error({
            title: '错误',
            message: error.message || '获取失败！'
          })
        }
      },
      async resetEditData(data = null) { // 重置编辑表单
        this.dialog.status = data ? 'update' : 'create'
        this.dialog.title = data ? '编辑' : '添加'
        // this.dialog.visible = true
        this.editInfo.id = undefined
        this.editInfo.disabled = false
        this.editInfo.data = JSON.parse(JSON.stringify(this.formParams))
        if (data) { // 编辑
          // this.editInfo.id = data.uuid
          this.editInfo.id = data.id
          await this.getRecordDetailData(data)
        }
      },
      async initEditDialog(data = null) { // 编辑－显示弹出框
        this.tabsSelectedId = 'recordEditBasic'
        await this.resetEditData(data)
      }
    },
    watch: {
      visible(newVal, oldVal) {
        if (newVal !== this.dialog.visible) {
          this.dialog.visible = newVal
          if (newVal) {
            this.initEditDialog(this.detailData)
          }
        }
      },
      'dialog.visible'(newVal, oldVal) {
        this.$emit('update:visible', newVal)
      },
      detailData: { // 详情数据
        handler: function(newVal, oldVal) {
          this.detailInfo = newVal
        },
        deep: true,
        immediate: true
      }
    },
    created() {
    },
    mounted() {
    }
  }
</script>

<style lang="scss" scoped>
  .edit-box {
    & /deep/ .el-dialog {
      min-width: 900px;
      max-width: 1200px;
    }

    & /deep/ .el-dialog__body {
      padding: 10px 20px 30px;
    }

    & /deep/ .el-tabs {
      .el-tabs__content {
        overflow: visible;
      }
    }
  }

  .editInfo {
    margin-right: 0;

    .el-cascader,
    .el-select {
      width: 100%;
    }
  }

  .el-upload-list--picture-card .el-upload-list__item {
    width: 70px;
    height: 70px;
  }

  .el-upload--picture-card {
    width: 70px;
    height: 70px;
    line-height: 68px;
    display: none;
  }

  .el-upload-list--picture-card .el-upload-list__item-actions span + span {
    margin-left: 8px;
  }

</style>
